<template>
  <el-select v-model="modelValue" filterable remote :remote-method="getOptions" remote-show-suffix
    :disabled="!companyId" :loading="loading">
    <el-option v-for="item in options" :key="item.community_id" :value="item.community_id"
      :label="item.name"></el-option>
  </el-select>
</template>

<script setup>
import { communityServer } from '@/api/customer'
import { ref, watch } from 'vue';
const props = defineProps({
  companyId: Number,
});
const modelValue = defineModel({
  type: Number
});
const loading = ref(false);
const options = ref([]);
const getOptions = async (kw, isInit) => {
  kw = (kw || '').trim();
  // 如果没有输入关键字且已有选项，则不重新获取
  if (!kw && options.value.length) return;
  if (!props.companyId) return;

  !isInit && (modelValue.value = null);
  loading.value = true;
  try {
    const { data } = await communityServer.get({
      company_id: props.companyId,
      size: 30,
      keyword: kw
    });
    options.value = data || [];
  } catch (error) {
    console.error('获取社区列表失败:', error);
  }
  loading.value = false;
};
getOptions('', true);

watch(
  () => props.companyId,
  () => {
    options.value = [];
    getOptions();
  },
)
</script>